<template>
  <div>
    <div class="tab-wrap">
      <div class="tab-inner">
        <div class="tab-banner">
          <img src="../../assets/jiaxiao_banner.jpg" />
        </div>
      </div>
      <div class="tab-filter">
        <div
          v-for="(item, index) in condition"
          :key="index"
          :class="{ checked: index == n }"
          @click="inquire(item.name, index)"
          class="tab-item"
        >
          <i class="iconfont icon-shunxu3"> {{ item.select }}</i>
        </div>
        <div
          :class="{ checked: choice }"
          @click="inquire(filtrate, 4)"
          class="tab-item"
        >
          <i class="iconfont van-icon-shaixuan">{{ filtrate }}</i>
        </div>
      </div>
      <!-- 开始 -->
      <div class="tab-position">
        <van-list
          class="box-cells"
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <van-cell
            center
            v-for="(item, i) in lists"
            :key="i"
            @click="href('/SchoolDetail', item.id)"
          >
            <template #icon>
              <img :src="item.imgtx" class="school-pic" alt />
            </template>
            <template #title>
              <div class="sch-heads">
                <div class="sch-name">{{ item.name }}</div>
                <img src="../../assets/ver-icon.png" alt />
              </div>
              <div class="sch-body justify">
                <div class="sch-left">
                  <div class="sch-raty">
                    <van-rate
                      v-model="item.xj"
                      color="#ffd21e"
                      void-icon="star"
                      void-color="#eee"
                      readonly
                    />
                    <!-- <span class="nn">{{ item.xj }}条</span> -->
                  </div>
                  <div class="sch-price-box">
                    <div class="sch-price">¥{{ item.bmf }}</div>
                    <div class="sch-ke">{{ item.bj }}</div>
                  </div>
                </div>
                <div class="sch-loc">
                  <div class="sch-area">{{ item.region }}</div>
                  <div class="sch-dist">{{ item.juli | numFilter }}km</div>
                </div>
              </div>
              <div class="sch-tags">
                <van-tag v-if="item.kczzis === '1'" type="primary"
                  >自有考场</van-tag
                >
                <van-tag v-if="item.ptssis === '1'" type="primary"
                  >班车接送</van-tag
                >
              </div>
            </template>
          </van-cell>
        </van-list>
      </div>

      <!-- 结束 -->
    </div>

    <!-- 筛选 -->
    <van-popup
      v-model="show"
      position="right"
      :style="{ height: '100%', width: '100%' }"
    >
      <van-nav-bar
        :z-index="999"
        :fixed="true"
        left-arrow
        @click-left="onClickLeft"
        :placeholder="true"
        title="搜索"
      ></van-nav-bar>
      <van-search
        v-model="value"
        action-text
        show-action
        shape="round"
        placeholder="请输入搜索关键词"
        input-align="center"
        background="#fff"
        maxlength="10"
      >
        <template #action>
          <div @click="onSearch">搜索</div>
        </template>
      </van-search>
      <!-- 当点击搜索按钮，查询出驾校时 -->
      <div v-if="conceal" class="search-history">
        <van-cell
          center
          v-for="(item, i) in school"
          :key="i"
          @click="href('/SchoolDetail', item.id)"
        >
          <template #icon>
            <img :src="item.imgtx" class="school-pic" alt />
          </template>
          <template #title>
            <div class="sch-heads">
              <div class="sch-name">{{ item.name }}</div>
              <img src="../../assets/ver-icon.png" alt />
            </div>
            <div class="sch-body justify">
              <div class="sch-left">
                <div class="sch-raty">
                  <van-rate
                    v-model="item.xj"
                    color="#ffd21e"
                    void-icon="star"
                    void-color="#eee"
                    readonly
                  />
                  <!-- <span class="nn">{{ item.xj }}条</span> -->
                </div>
                <div class="sch-price-box">
                  <div class="sch-price">¥{{ item.bmf }}</div>
                  <div class="sch-ke">{{ item.bj }}</div>
                </div>
              </div>
              <div class="sch-loc">
                <div class="sch-area">{{ item.region }}</div>
                <div class="sch-dist">{{ item.juli | numFilter }}km</div>
              </div>
            </div>
            <div class="sch-tags">
              <van-tag v-if="item.kczzis === '1'" type="primary"
                >自有考场</van-tag
              >
              <van-tag v-if="item.ptssis === '1'" type="primary"
                >班车接送</van-tag
              >
            </div>
          </template>
        </van-cell>
      </div>
      <!-- 当不点击搜索时，选择条件不隐藏 -->
      <div v-else class="screen">
        <!-- 所属区域 -->
        <div class="students-here">
          <p>驾校服务</p>
          <div class="screen-list">
            <div
              v-for="(item, index) in schoolserve"
              :key="index"
              :class="{ select_hue: item.active }"
              @click="ExaminationRoom(item.id, item)"
            >
              {{ item.title }}
            </div>
            <!-- <div>班车接送</div> -->
          </div>
        </div>
        <!-- 优惠活动 -->
        <div class="students-here">
          <p>驾照类型</p>
          <div class="screen-list">
            <div
              v-for="(item, index) in licensetype"
              :key="index"
              :class="{ select_hue: colorIndex === index }"
              @click="TypeOf(index)"
            >
              {{ item }}
            </div>
          </div>
        </div>

        <!-- 附加服务 -->
        <div class="students-here">
          <p>附加服务</p>
          <div class="screen-list">
            <div
              v-for="(item, index) in service"
              :key="index"
              :class="{ select_hue: item.active }"
              @click="AccessorialService(item.id, item)"
            >
              {{ item.title }}
            </div>
          </div>
        </div>
      </div>
      <!-- 底部按钮 -->
      <div v-if="!conceal" class="btn-ensure" @click="confirm">确定</div>
    </van-popup>
  </div>
</template>

<script>
import { Toast } from "vant";
import {
  drivingSchool,
  globalSSearch,
  ScreenOut
} from "../../assets/js/api/apply";
export default {
  name: "FindSchool",
  data() {
    return {
      // aptitude: false,
      // 条件
      condition: [
        {
          select: "推荐",
          name: ""
        },
        {
          select: "距离",
          name: "juli"
        },
        {
          select: "价格",
          name: "bmf"
        },
        {
          select: "评价",
          name: "xj"
        }
      ],
      n: 0,
      //
      // 开始
      lists: [],
      loading: false,
      finished: false,
      baseURL: "",
      filtrate: "筛选",
      // 结束
      //lists: [],
      SPagination: 0, // 找驾校传的页数
      precision: null, // 精度
      // 114.495438,38.040065
      dimensionality: null, // 维度
      // apart: [], // 来储存计算的经纬度
      parameter: "", // 用来储存的参数
      rank: "desc", // 排序方式
      show: false, // 点击筛选时弹出
      value: "", // 筛选中的输入框
      school: [], // 筛选中搜索后查询出的驾校
      conceal: false, // 控制驾校和筛选条件的显示隐藏
      // 驾校服务
      schoolserve: [
        {
          title: "自有考场",
          id: "1"
        },
        {
          title: "班车接送",
          id: "2"
        }
      ],
      servicer: [], // 定义一个数组，来储存选择的驾校服务
      // select 选择，是为了控制选择开场的
      colorIndex: -1,
      choice: false, // 点击筛选之后给筛选添加的颜色
      // 驾校类型
      licensetype: ["C1/C2/C3", "A1/A2", "B1/B2", "D/E/F"],
      vehicle: 0, // 定义一个变量，来储存用户选的类型
      // 附加服务
      service: [
        { title: "先学车后付费", id: 1 },
        { title: "按学时付费", id: 2 },
        { title: "支持贷款学车", id: 3 },
        { title: "支持线上转学", id: 4 },
        { title: "优惠券", id: 5 }
      ],
      supplementary: [] // 用来储存附加服务的
    };
  },
  filters: {
    numFilter(value) {
      let realVal = "";
      if (!isNaN(value) && value !== "") {
        // 截取当前数据到小数点后两位
        realVal = parseFloat(value).toFixed(2);
      } else {
        realVal = "--";
      }
      return realVal;
    }
  },
  mounted() {
    let dsBridge = require("dsbridge");
    dsBridge.call("goBack", "", function() {
      this.show = false;
      this.servicer = [];
      this.vehicle = [];
      this.supplementary = [];
      this.colorIndex = -1;
      this.addActive1();
      this.addActive();
    });
    this.getGpsLocation();
    this.addActive();
    this.addActive1();
  },
  methods: {
    // 当点击确定按钮时，执行的操作

    confirm() {
      this.lists = [];
      if (this.conceal) {
        this.lists = this.school;
        this.show = false;
        this.choice = true;
      } else {
        this.precision = sessionStorage.getItem("jd");
        this.dimensionality = sessionStorage.getItem("wd");
        let obj = {
          zykcbcjs: this.servicer,
          cx: this.vehicle,
          fjfwArray: this.supplementary,
          orderByColumn: this.parameter,
          isAsc: this.rank,
          jd: this.precision,
          wd: this.dimensionality
        };
        // console.log(obj);
        ScreenOut(obj).then(res => {
          if (res.data.length == 0) {
            Toast("未查询到有关驾校");
            return;
          }
          // console.log(res);
          this.lists = res.data;
          this.choice = true;
          this.show = false;
          this.servicer = [];
          this.vehicle = [];
          this.supplementary = [];
          this.colorIndex = -1;
          this.addActive1();
          this.addActive();
        });
      }
    },

    addActive1() {
      this.service.forEach(item => {
        this.$set(item, "active", false);
      });
    },
    // 当选择附加服务时执行的操作
    AccessorialService(id, item) {
      // console.log(id);
      if (!item.active) {
        item.active = true;
        this.supplementary.push(id);
        // console.log("选择");
      } else {
        item.active = false;
        for (let i = 0; i < this.supplementary.length; i++) {
          if (this.supplementary[i] == id) {
            this.supplementary.splice(i, 1);
          }
        }
        // console.log("取消");
      }
      // console.log(this.supplementary);
    },

    // 当点击驾照类型的时候执行的操作
    TypeOf(index) {
      if (this.colorIndex != index) {
        this.colorIndex = index;
        this.vehicle = index + 1;
      } else {
        this.colorIndex = -1;
        this.vehicle = 0;
      }
      // console.log(index);
    },

    /*给schoolserve的每一个对象添加active属性，需要用到this.$set（'对象','键值','value'） */
    addActive() {
      this.schoolserve.forEach(item => {
        this.$set(item, "active", false);
      });
    },
    // 筛选之后点击驾校服务的时候选择
    ExaminationRoom(id, item) {
      // console.log(id);
      if (!item.active) {
        item.active = true;
        this.servicer.push(id);
        // console.log("选择");
      } else {
        item.active = false;
        for (let i = 0; i < this.servicer.length; i++) {
          if (this.servicer[i] == id) {
            this.servicer.splice(i, 1);
          }
        }
        // console.log("取消");
      }
      // console.log(this.servicer);
    },

    onSearch() {
      // 类型默认的是驾校，当搜索内容是空的时候，提示内容
      if (this.value == "") {
        Toast("请输入搜索内容");
        return;
      }
      // console.log(this.classify);
      // console.log(this.value);
      let obj = {
        type: 1,
        keyWord: this.value,
        jd: this.precision,
        wd: this.dimensionality
      };
      globalSSearch(obj).then(res => {
        if (res.data.length == 0) {
          Toast("未查询到有关驾校");
          return;
        }
        // console.log(res);
        this.conceal = true;
        this.school = res.data;
      });
    },

    inquire(lid, index) {
      // console.log("点击");

      //console.log(lid);
      this.finished = false;
      this.SPagination = 0;
      this.parameter = "";
      this.choice = false;
      this.n = index; //改变this指向app
      if (lid === "") {
        // console.log("点击1");
        this.lists = [];
        this.rank = "desc";
        this.onLoad();
      } else if (lid == "juli") {
        this.lists = [];
        this.parameter = lid;
        this.rank = "asc";
        this.onLoad();
      } else if (lid == "筛选") {
        // console.log(index);
        this.onLoad(lid);
        this.show = true;
      } else if (lid == "bmf") {
        // console.log("价格");
        this.lists = [];
        this.parameter = lid;
        this.rank = "asc";
        this.onLoad();
      } else {
        this.lists = [];
        this.parameter = lid;
        this.rank = "desc";
        this.onLoad();
      }
    },
    onLoad(lid) {
      // console.log(lid);
      // 异步更新数据
      if (lid != undefined) {
        this.finished = true;
        return;
      }
      let pageSize = 10;
      let pageNum = this.SPagination + 1;
      this.SPagination++;
      let obj = {
        pageSize: pageSize,
        pageNum: pageNum,
        orderByColumn: this.parameter,
        isAsc: this.rank,
        jd: this.precision,
        wd: this.dimensionality
      };
      // console.log(obj);
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      drivingSchool(obj).then(res => {
        let extent;
        let list = res.data;
        //            Toast(list)
        for (let i = 0; i < list.length; i++) {
          this.lists.push(list[i]);
          extent = list[i].totalcount;
        }
        // console.log(this.lists);
        // 加载状态结束
        this.loading = false;
        // 数据全部加载完成
        if (this.lists.length >= extent) {
          this.finished = true;
        }
      });
    },
    getGpsLocation() {
      let jd = sessionStorage.getItem("jd");
      let wd = sessionStorage.getItem("wd");

      if (
        null == jd ||
        null == wd ||
        0 == jd ||
        0 == wd ||
        "null" == jd ||
        "null" == wd ||
        "0" == jd ||
        "0" == wd
      ) {
        let _this = this;
        let dsBridge = require("dsbridge");
        dsBridge.call("tellHtml_loc", "", function(data) {
          var jwd = "";
          try {
            jwd = JSON.parse(data);
          } catch (err) {
            _this.getGpsLocation();
          }
          // Toast(jwd)
          if (jwd == "") {
            sessionStorage.setItem("jd", "114.495438");
            sessionStorage.setItem("wd", "38.040065");
            sessionStorage.setItem("city", "湘潭市");
            sessionStorage.setItem("LocationCity", "正在定位");
          } else {
            sessionStorage.setItem("jd", jwd.lgt);
            sessionStorage.setItem("wd", jwd.lat);
            sessionStorage.setItem("city", jwd.city);
            sessionStorage.setItem("LocationCity", jwd.address);
          }
          this.getGpsLocation();
        });
      } else {
        if (null != jd) {
          sessionStorage.setItem("jd", jd);
          this.precision = jd; // 精度
        }
        if (null != jd) {
          sessionStorage.setItem("wd", wd);
          this.dimensionality = wd; // 维度
        }
      }
    },
    href(url, lid, id) {
      // console.log("我是驾校：" + id);
      if (id) {
        this.$router.push({
          path: `${url}/${lid}/${id}`
        });
      } else {
        this.$router.push({ path: `${url}/${lid}` });
        this.show = false;
      }
    },
    // 调通手机号码，实现打电话功能
    callPhone(phoneNumber) {
      window.location.href = "tel://" + phoneNumber;
      // console.log(this.Phone);
    },
    onClickLeft() {
      this.show = false;
      this.servicer = [];
      this.vehicle = [];
      this.supplementary = [];
      this.colorIndex = -1;
      this.addActive1();
      this.addActive();
      this.conceal = false;
      this.value = "";
    }
  }
};
</script>

<style></style>
